package com.yingxin.yx.framework.jwt;

import com.yingxin.yx.framework.user.core.IUserSupport;
import com.yingxin.yx.framework.user.dto.TokenDto;
import com.yingxin.yx.framework.user.dto.UserDto;
import com.yingxin.yx.framework.user.exception.UserAuthException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author fanchao
 */
@Component
public class TokenSupport {

    @Autowired
    private JwtTokenPairFactory jwtTokenPairFactory;

    @Autowired
    private IUserSupport userSupport;

    public TokenDto getAccessToken(UserDto user) {
        JwtTokenPair tokenPair = jwtTokenPairFactory.create(user);
        TokenDto token = new TokenDto();
        token.setUserId(user.getUserId());
        token.setToken(tokenPair.getAccessToken());
        token.setRefreshToken(tokenPair.getRefreshToken());
        token.setExpireTime(tokenPair.getExpireTime());
        token.setUsername(user.getUsername());
        // token.setRealName(user.getStaffName());
        token.setStaffName(user.getStaffName());
        token.setIsAppLogon(user.getIsAppLogon());
        return token;
    }

    /**
     * 开放接口 token
     * @param user
     * @return
     */
    public TokenDto getOpenApiAccessToken(UserDto user) {
        JwtTokenPair tokenPair = jwtTokenPairFactory.createOpenApiToken(user);
        TokenDto token = new TokenDto();
        token.setToken(tokenPair.getAccessToken());
        token.setRefreshToken(tokenPair.getRefreshToken());
        token.setExpireTime(tokenPair.getExpireTime());
        token.setUsername(user.getUsername());
        token.setStaffName(user.getStaffName());
        return token;
    }


    public TokenDto getRefreshToken(String refreshToken) {
        // userId
        JwtPayload payload = JwtHelper.getJwtPayload(refreshToken);
        String userId = payload.getSub();
        // 根据userId获取user
        UserDto user = userSupport.getUser(userId);
        if (user == null) {
            throw new UserAuthException();
        }
        // 认证refreshToken
        JwtHelper.verifyRefreshToken(user.getJwtPrivateKey(), refreshToken);
        // 创建新的 jwtToken
        JwtTokenPair tokenPair = jwtTokenPairFactory.create(user);
        // TokenDto
        TokenDto token = new TokenDto();
        token.setUserId(user.getUserId());
        token.setToken(tokenPair.getAccessToken());
        token.setRefreshToken(tokenPair.getRefreshToken());
        token.setExpireTime(tokenPair.getExpireTime());
        token.setUsername(user.getUsername());
        token.setRealName(user.getStaffName());
        token.setIsAppLogon(user.getIsAppLogon());
        return token;
    }


}
